package com.wuyou.single.common.security.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.wuyou.single.common.api.CommonResult;
import com.wuyou.single.common.api.ResultCode;
import com.wuyou.single.common.util.ServletUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description 认证失败处理类
 * @Author 无忧
 * @Date 2024/6/11 23:03
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 认证失败
        String msg = StrUtil.format("请求访问{}，认证失败，无法访问系统资源", request.getRequestURI());
        ServletUtils.renderString(response, JSONObject.toJSONString(CommonResult.failed(ResultCode.UNAUTHORIZED, msg)));
    }
}
